/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.pay.handler.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bblocks.enums.SysEnum;
import com.bblocks.exception.ServiceException;
import com.bblocks.util.ServletUtils;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.pig4cloud.pigx.pay.entity.DTO.PayParamsDTO;
import com.pig4cloud.pigx.pay.entity.PayChannel;
import com.pig4cloud.pigx.pay.entity.PayTradeOrder;
import com.pig4cloud.pigx.pay.mapper.PayChannelMapper;
import com.pig4cloud.pigx.pay.mapper.PayTradeOrderMapper;
import com.pig4cloud.pigx.pay.service.PayChannelService;
import com.pig4cloud.pigx.pay.service.PayTradeOrderService;
import com.pig4cloud.pigx.pay.utils.ChannelPayApiConfigKit;
import com.pig4cloud.pigx.pay.utils.OrderStatusEnum;
import com.pig4cloud.pigx.pay.utils.PayChannelNameEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lengleng
 * @date 2019-05-31
 * <p>
 * 支付宝支付支付（wap）
 */
@Slf4j
@Service("ALIPAY_WAP")
@AllArgsConstructor
public class AlipayWapPayOrderHandler extends AbstractPayOrderHandler {

	private final PayTradeOrderService payTradeOrderService;

	private final PayTradeOrderMapper tradeOrderMapper;

	private final PayChannelService payChannelService;

	private final HttpServletRequest request;

	private final HttpServletResponse response;

	/**
	 * 准备支付参数
	 */
	@Override
	public PayChannel preparePayParams(Long tenantId) {
		PayChannel channel = payChannelService.getChannel(PayChannelNameEnum.ALIPAY_WAP,tenantId);

		if (channel == null) {
			throw new IllegalArgumentException("支付宝Wap支付渠道配置为空");
		}

		JSONObject params = JSONUtil.parseObj(channel.getParam());
		AliPayApiConfig aliPayApiConfig = AliPayApiConfig.builder().setAppId(channel.getAppId())
				.setPrivateKey(params.getStr("privateKey")).setCharset(CharsetUtil.UTF_8)
				.setAliPayPublicKey(params.getStr("publicKey")).setServiceUrl(params.getStr("serviceUrl"))
				.setSignType("RSA2").build();
		AliPayApiConfigKit.setThreadLocalAliPayApiConfig(aliPayApiConfig);
		return channel;
	}



	public PayTradeOrder createTradeOrder(PayParamsDTO payInfo){
		PayTradeOrder tradeOrder = this.setTradeOrderBase(payInfo);

		payTradeOrderService.saveOne(tradeOrder);
		return tradeOrder;
	}



	/**
	 * 调起渠道支付
	 * @param tradeOrder 交易订单
	 */
	@Override
	public PayTradeOrder collection( PayTradeOrder tradeOrder) {
		/*AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setBody(tradeOrder.getBody());
		model.setSubject(tradeOrder.getBody());
		model.setOutTradeNo(tradeOrder.getPayNo());
		model.setTimeoutExpress("30m");

		// 分转成元 并且保留两位
		model.setTotalAmount(NumberUtil.div(tradeOrder.getAmount().toString(), "100", 2).toString());
		model.setProductCode("QUICK_MSECURITY_PAY");
		model.setPassbackParams(String.valueOf(tradeOrder.getTenantId()));
		try {
			log.info("拉起支付宝wap 支付参数 {}", model);
			AliPayApi.wapPay(response, model, ChannelPayApiConfigKit.get().getReturnUrl(),
					ChannelPayApiConfigKit.get().getNotifyUrl() + "/admin/notify/ali/callbak");
		}
		catch (AlipayApiException e) {
			log.error("支付宝手机支付失败", e);


		}
		catch (IOException e) {
			log.error("支付宝手机支付失败", e);
		}
		return tradeOrder;*/
		throw new ServiceException(SysEnum.ERR_NO_REALIZE);
	}


	public Object pay(PayTradeOrder tradeOrder){
		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel ();
		model.setBody(tradeOrder.getBody());
		model.setSubject(tradeOrder.getSubject());
		model.setOutTradeNo(tradeOrder.getPayNo());
		model.setTimeoutExpress(tradeOrder.getExpireTime()+"m");

		// 分转成元 并且保留两位
		model.setTotalAmount(NumberUtil.div(tradeOrder.getAmount().toString(), "100", 2).toString());
		model.setProductCode("QUICK_WAP_PAY");
		model.setPassbackParams(formExtraParams(tradeOrder.getTenantId(),tradeOrder.getChannelId()));
		try {
			log.info("申请支付宝app 支付参数 {}", model);
			AliPayApi.wapPay(response, model, ChannelPayApiConfigKit.get().getReturnUrl(),
					ChannelPayApiConfigKit.get().getNotifyUrl());
			return null;
		}
		catch (AlipayApiException e) {
			log.error("支付宝手机支付失败", e);
			throw new ServiceException(SysEnum.SYS_ERROR.getCode(),"支付系统故障，请稍后再试！");
		}
		catch (Exception e) {
			log.error("支付宝手机支付失败", e);
			throw new ServiceException(SysEnum.SYS_ERROR.getCode(),"支付系统故障，请稍后再试！");
		}
	}

}
